<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Content;

/**
 * ContentSearch represents the model behind the search form about `app\models\Content`.
 */
class ContentSearch extends Content
{
    public $channel_name;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'create_time', 'pub_time', 'manager_id'], 'integer'],
            [['title', 'thumb', 'detail', 'copyfrom', 'summary'], 'safe'],
            [['channel_name'],'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Content::find()->orderBy('create_time desc');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }
        if($this->channel_name>0){
            $joins = Cncjoin::find()->where(['channel_id'=>$this->channel_name])->indexBy('content_id')->asArray()->all();

            if(!empty($joins)) {
                $query->andWhere(['in','id',array_keys($joins)]);
            } else {
                $query->andWhere(['in','id',[]]);

            }
        }
        $query->andFilterWhere([
            'id' => $this->id,
            'create_time' => $this->create_time,
            'pub_time' => $this->pub_time,
            'manager_id' => $this->manager_id,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'thumb', $this->thumb])
            ->andFilterWhere(['like', 'detail', $this->detail])
            ->andFilterWhere(['like', 'copyfrom', $this->copyfrom])
            ->andFilterWhere(['like', 'summary', $this->summary]);

        return $dataProvider;
    }
}
